package com.uxwine.alarm;

import java.util.ArrayList;
import java.util.List;

import com.uxwine.alarm.main.Alarm;
import com.uxwine.alarm.main.Alarmer;
import com.uxwine.alarm.main.DBAlarms;
import com.uxwine.cmm.BaseService;

import android.content.Context;
import android.content.Intent;
import android.text.format.DateFormat;
import android.widget.Toast;

public class AlarmService extends BaseService {
	
	private Alarmer mAlarmer;
	private boolean mbInitAlarms;

	@Override
	public void onCreate() {
		super.onCreate();
		mAlarmer = new Alarmer(this);
		mbInitAlarms = false;
	}

	@Override
	protected void onServiceCmd(Intent i) {
		
		String action = i.getAction();
		if(ACTION_START_ALRAM.equals(action))
		{
			int id = i.getIntExtra("alarm", -1);
			if(-1 != id)
				setAlarm(id, false);
		}
		else if(ACTION_CANCEL_ALRAM.equals(action))
		{
			int id = i.getIntExtra("alarm", -1);
			if(-1 != id)
				setAlarm(id, true);
		}		
	}

	@Override
	protected void onServiceStart() {
		new Thread(new LoadingWork()).start();
	}
	
	public void setAlarm(int id, boolean bCancel)
	{
		DBAlarms db = new DBAlarms(this, !bCancel);
		Alarm a = db.get(id);
		if(bCancel)
		{
			mAlarmer.cancel(a);
		}
		else
		{
			if(!mAlarmer.start(a))
			{
				a.setEffective(false);
				db.update(a);
			}			
		}
		db.close();
	}
	
	protected synchronized void initAllAlarms() {
		if(!mbInitAlarms)
			return;
		DBAlarms db = new DBAlarms(this, true);
		List<Alarm> alarms = db.getAll();
		for(Alarm a : alarms)
		{
			if(!mAlarmer.start(a))
			{
				a.setEffective(false);
				db.update(a);
			}
		}
		db.close();
		mbInitAlarms = true;
	}
	
	private class LoadingWork implements Runnable
	{

		@Override
		public void run() {
			initAllAlarms();
		}
		
	}

}
